import backtrader as bt
import numpy as np
import pandas as pd
import traceback

from indicators.wave_index_ind import wave_index_ind


class HigBiLi(bt.Strategy):
    # 策略参数
    params = dict(
        period=20,  # 均线周期
        look_back_days=30,
        printlog=False,
        period_ema_fast=10,
        period_ema_slow=100,
        short_window=30,
        long_window=60,
        N1=6,
        N2=50,
        N3=25,
        wave_window=20,
        wave_two_window=50,
        wave_three_window=70,
    )
    def __init__(self):
        try:
         for data in self.datas:
           data.N_High = bt.ind.Highest(data.high, period=self.p.N1)

           # 五日移动平均线
           data.sma25 = bt.indicators.SimpleMovingAverage(data, period=25)


        except Exception as e:
            traceback.print_exc()

        #遍历所有股票,计算20日均线
        #for data in self.datas:

    def notify_order(self, order):
        """
        订单状态处理

        Arguments:
            order {object} -- 订单状态
        """
        if order.status in [order.Submitted, order.Accepted]:
            # 如订单已被处理，则不用做任何事情
            return

        # 检查订单是否完成
        if order.status in [order.Completed]:
            if order.isbuy():
                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
                #print('BUY成交, 执行价={0}, {1}'.format(order.executed.price, order.executed.size))
            #elif order.issell():
                #print('SELL成交, 执行价={0}, {1}'.format(order.executed.price, order.executed.size))
            self.bar_executed = len(self)
        # 订单因为缺少资金之类的原因被拒绝执行
        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')
        # 订单状态处理完成，设为空
        self.order = None

    def notify_trade(self, trade):
        """
        交易成果

        Arguments:
            trade {object} -- 交易状态
        """
        if not trade.isclosed:
            return

        # 显示交易的毛利率和净利润
        self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                 (trade.pnl, trade.pnlcomm), doprint=True)



    def next(self):
        #print(len(self))

        total_value = self.broker.getvalue()
        p_value = total_value*0.9/10
        for data in self.datas:
          #print(len(data)," ",data.buflen())

          if len(data) == (data.buflen()) :


            pos = self.getposition(data).size
            #data.close[0] > data.N_High[0] and
            if not pos :
                if (((data.N_High[0]-data.high[0])/data.N_High[0])>0.16) :
                            #print(data.datetime.date(0), " ", data.close[0])
                            print(data._name)
                            #self.order = self.buy ( data=data )
                            #self.order = self.close(exectype=bt.Order.StopTrail, trailpercent=0.2)
                            #self.order = self.sell(data=data,exectype=bt.Order.StopTrail, trailamount=1000)
            #if pos!=0 :
            #    if  (   data.rsi >50  ):
            #        self.close ( data = data )
    def log(self, txt, dt=None,doprint=False):
        if self.params.printlog or doprint:
            dt = dt or self.datas[0].datetime.date(0)
            print(f'{dt.isoformat()},{txt}')
    #  or self.getFrontB( data, 3) == True
    def getFrontB(self, data,  end):
        for i in range(1, end):
            #print(data.sma25[-i],"",data.close[-i])
            if data.sma25[-i] < data.close[-i]:
                return False

        return True



    #记录交易收益情况（可省略，默认不输出结果）
    #def notify_trade(self,trade):
    #    if not trade.isclosed:
    #        return
    #    self.log(f'策略收益：\n毛收益 {trade.pnl:.2f}, 净收益 {trade.pnlcomm:.2f}')
